package cn.tedu.boot11.controller;

import cn.tedu.boot11.entity.User;
import cn.tedu.boot11.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/user/reg")
    @ResponseBody
    public String reg(User user){
        System.out.println("user = " + user);

        //获取数据库连接
        try(Connection conn=DBUtils.getConn()){
            String sql="insert into user values(null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);

            //替换?
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNick());
            ps.executeUpdate();

        }catch (SQLException e){
            e.printStackTrace();
        }
        return "注册成功!";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String login(User user){
        System.out.println("user = " + user);
        //获取数据库连接
        try(Connection conn=DBUtils.getConn()){
            String sql="select password from user where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());

            //获取
            ResultSet resultSet = ps.executeQuery();
            if(resultSet.next()) {
                String password = resultSet.getString(1);
                if(password.equals(user.getPassword())){
                   return "登陆成功!";
                }
                    return "密码错误";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return "用户名不存在!";
    }

}
